import SimpleSchedule from ".";

let Schedule = {}

Schedule.data = {
  mode: 'RequestAnimationFrame',
  timerTask: null,
  timerTaskBackend: null,
  _initTime: new Date().getTime(),
  isParsing: false,
  callBack: null,
  tasks: {
    'testTask': 3000
  },
  taskRecord: {
  },
}

Schedule.handler = () => {
  let realTime = new Date().getTime()
  for (let taskId in Schedule.data.tasks) {
    if(Schedule.data.isParsing) {
      break
    }
    if((realTime - Schedule.data.taskRecord[taskId]) >= Schedule.data.tasks[taskId]) {
      Schedule.data.callBack({taskId: taskId, realTime, mode: Schedule.data.mode})
      Schedule.data.taskRecord[taskId] = realTime
    }
  }
}
/**
 * 前台轮询方式
 */
Schedule.requestAnimationTimer = () => {
  Schedule.handler()
  Schedule.data.timerTask = requestAnimationFrame(Schedule.requestAnimationTimer)
},
/**
 * 窗口非激活状态下的轮询
 */
Schedule.setIntervalTimer = () => {
  Schedule.data.timerTaskBackend = setInterval(() => {
    Schedule.handler()
  },20)
},
/**
 * 退出定时
 */
Schedule.cancle = () => {
  if (Schedule.data.mode === 'INTERVAL') {
    clearInterval(Schedule.data.timerTask)
  } else if (Schedule.data.mode === 'ANIMATION') {
    cancelAnimationFrame(this.data.timerTask)
  }
}
/**
 * 开启定时
 */
Schedule.start = () => {
  Schedule.requestAnimationTimer()
}
Schedule.parse = () => {
  Schedule.data.isParsing = true
}
Schedule.init = (params) => {
  if (typeof params === 'object') {
    for (let key in params) {
      if (params[key] != null) {
        Schedule.data[key] = params[key] 
      }
    }
  }
  for (let key in Schedule.data.tasks) {
    Schedule.data.taskRecord[key] = 0
  }
  var bowhidden='hidden' in document? 'hidden' : 'webkithidden' in document? 'webkithidden': 'mozhidden' in document ? 'mozhidden' : null
  var vibchage= 'visibilitychange' || 'webkitvisibilitychange' || 'mozvisibilitychange'
  document.addEventListener(vibchage, () => {
    // 激活
    if (!document[bowhidden]) {
      Schedule.data.mode = 'RequestAnimationFrame'
      if(Schedule.data.timerTaskBackend != null) {
        clearInterval(Schedule.data.timerTaskBackend)
      }
    } else { // 隐藏
      Schedule.data.mode = 'Interval'
      Schedule.setIntervalTimer()
    }
  })
}

export default Schedule